require('../register_alias')
const _ = require('lodash')

const fetch = require('./fetch')
const log = require('./log')

const { postModel } = require('@/mongodb/model')
const params = {
  category: '57be7c18128fe1005fa902de',
  after: '',
  order: 'POPULAR',
  tags: [],
}

const _log = (v, index, endCursor) => {
  const logData = index + '. ' + v.originalUrl + ',  标题:' + v.title + ', ' + endCursor + '\r\n'
  log(logData)
}

const isExist = ({ id }) => {
  return postModel.findOne({ id })
}

const request = (params) => {
  const { category, after, order, tags } = params
  fetch
    .post('/query', {
      operationName: '',
      query: '',
      variables: { tags, category, first: 20, after, order },
      extensions: { query: { id: '653b587c5c7c8a00ddf67fc66f989d42' } },
    })
    .then(async (res) => {
      const {
        data: {
          data: {
            articleFeed: {
              items: {
                edges,
                pageInfo: { endCursor },
              },
            },
          },
        },
      } = res

      for (let i in edges) {
        const v = edges[i]
        _log(v.node, i, endCursor)
        const entity = v.node
        entity.tags = entity.tags.map((item) => item.title)
        entity.user = entity.user.username
        const exist = await isExist({ id: entity.id })
        console.log(exist)

        if (!exist) {
          postModel.create(entity, (r, j) => {
            console.log(r, j)
          })
        }
      }

      setTimeout(() => {
        params.after = endCursor
        request(params)
      }, 10000)
    })
    .catch((err) => {
      console.log(err)
    })
}

request(params)
